//
//  ComposeController.swift
//  MyWeiBo
//
//  Created by mac on 15/3/5.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class ComposeController: UIViewController {
    
    @IBOutlet weak var textView: ComposeTextView!
    @IBOutlet weak var toolBarBottomConstraint: NSLayoutConstraint!

    /// 表情键盘控制器
    var emotionViewController: EmotionKeyboardController?
    
    @IBOutlet weak var composeButton: UIBarButtonItem!
    
    
    class func composeNavigationController() -> WBNavigationController {
        let nav = UIStoryboard(name: "ComposeController", bundle: nil).instantiateInitialViewController() as! WBNavigationController
        nav.topViewController.title = "发微博"
        return nav
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpKeyBoardConfig()
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: 界面点击事件处理
    @IBAction func emojiButtonDidClicked(sender: UIButton) {
        textView.resignFirstResponder()
        if textView.inputView == nil {
            // 设置输入视图
            let emoView = emotionViewController?.view
            textView.inputView = emoView
            println(emoView)
        } else {
            textView.inputView = nil
        }
        
        textView.becomeFirstResponder()
    }
    
    @IBAction func cancelBarButtonDidClicked(sender: UIBarButtonItem) {
        self.view.endEditing(true)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func composeButtonDidClicked(sender: UIBarButtonItem) {
        self.view.endEditing(true)
        SVProgressHUD.show()
        let text = textView.rawTextString()
        StatusTool.sendStatusWithStatusText(text) { (result, error) -> () in
            SVProgressHUD.dismiss()
            if result == nil && error == nil {
                NSNotificationCenter.defaultCenter().postNotificationName(WB_SwithcToOAuthController_Notification, object: nil)
            } else if error == nil {
                // 发布成功
                SVProgressHUD.showErrorWithStatus("发布成功", maskType: .Gradient)
                self.dismissViewControllerAnimated(true, completion: nil)
            } else {
                // 发布失败
                println(error)
                SVProgressHUD.showErrorWithStatus("发布失败")
            }
        }
    }
    
    
}

// MARK: 键盘处理
extension ComposeController {
    // MARK: 键盘处理
    func setUpKeyBoardConfig() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillHideNotification, object: nil)
        
        // 添加键盘控制器
        let emoVC = EmotionKeyboardController.emotionKeyboardController()
        self.addChildViewController(emoVC)
        emotionViewController = emoVC
        emotionViewController?.delegate = self
    }
    
    func keyBoardChange(notification: NSNotification) {
        let animationTime: NSTimeInterval = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        if notification.name == UIKeyboardWillHideNotification {
            toolBarBottomConstraint.constant = 0
            UIView.animateWithDuration(animationTime) {
                self.view.layoutIfNeeded()
            }
        } else if notification.name == UIKeyboardWillShowNotification {
            let keyBoardHeight = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size.height
            toolBarBottomConstraint.constant = keyBoardHeight
            UIView.animateWithDuration(animationTime) {
                self.view.layoutIfNeeded()
            }
        }
    }
}

// MARK: EmotionKeyboardDelegate
extension ComposeController: EmotionKeyboardDelegate {
    
    func emotionKeyboardDidSelected(emoticon: Emoticon) {
        // 如果是删除按钮直接删除
        if emoticon.isDelete {
            self.textView.deleteBackward()
            return
        }
        // 想办法来根据表情的判断应该传什么参数来调用代理方法
        if !emoticon.isEmoji {
            let currLength = (self.textView.rawTextString() as NSString).length
            let range = NSMakeRange(0, currLength)
            if !textView(self.textView, shouldChangeTextInRange: range, replacementText: emoticon.chs!) {
                return
            }
        }
        textView.inputEmoticon(emoticon)
        textViewDidChange(self.textView)
    }
}

// MARK: UITextViewDelegate
extension ComposeController: UITextViewDelegate,UIScrollViewDelegate {
    // MARK: UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        // 处理什么时候隐藏提示文字
        let isNoLength = (textView.attributedText.length == 0)
        self.textView.placeHoderTextlabel?.hidden = !isNoLength
        self.composeButton.enabled = !isNoLength
    }
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        // 特殊控制字符要进行特殊判断
        if text.isEmpty || text == "\n" {
            return true
        }
        let currLength = (self.textView.rawTextString() as NSString).length
        // 处理字数限制
        if (currLength + (text as NSString).length ) > self.textView.maxTextCountInTextView {
            return false
        }
        return true
    }
    // MARK: UIScrollViewDelegate
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}

